<?php

namespace app\admin\controller;

use wechat\src\WeChat;
use think\Db;
/**
 * 微信用户设置，
 */
class Wechatuser extends base
{

    protected $wechat;

    //前置方法
    protected $beforeActionList = [
        'map' => ['only' => 'index,userlist'],
    ];

    /**
     * 搜索
     */
    protected function map()
    {
        if ($this->request->isGet()) {
            $data = $this->request->param();
            $this->datas = array();
            if (isset($data['times'])) {
                $times = explode('到', $data['times']);
                if (count($times) == 2) {
                    $this->datas['subscribe_time'] = ['between', [strtotime($times[0]), strtotime($times[1]) + 86400]];
                }
            }
            if (isset($data['nickname']) && !empty($data['nickname'])) {
                $this->datas ['nickname'] = ['like', '%' . $data['nickname'] . '%'];
            }
            if (isset($data['sex'])&& $data['sex'] != 0) {
                $this->datas ['sex'] = $data['sex'];
            }
            if (isset($data['need']) && $data['need'] == 1) {
                $this->datas['last_time'] = ['>', (time() - (86400 * 2))];
            }

            $this->datas ['subscribe'] = '1';
        }

    }


    public function _initialize()
    {
        $this->wechat = (new WeChat);
        $this->wechat->valid();

    }


    /**
    用户列表
     */
    public function userlist(){

        /** 写入数据库*
        $data = $this->wechat->instance('user')->getUserLists();
        $value['user_list'] = null;
        foreach ($data['data']['openid'] as $key) {
        $value['user_list'][] = [
        "openid" => "$key",
        "lang" => "zh_CN",
        ];
        }
        $user = $this->wechat->instance('user')->getUserInfoLists($value);

        foreach($user['user_info_list'] as $key =>$value){

        $list[$key]['openid'] = $value['openid'];
        $list[$key]['groupid'] = $value['groupid'];
        $list[$key]['subscribe'] = $value['subscribe'];
        $list[$key]['nickname'] = $value['nickname'];
        $list[$key]['sex'] = $value['sex'];
        $list[$key]['city'] = $value['city'];
        $list[$key]['country'] = $value['country'];
        $list[$key]['province'] = $value['province'];
        $list[$key]['headimgurl'] = $value['headimgurl'];
        $list[$key]['subscribe_time'] = $value['subscribe_time'];
        }
        $res= db('wuser')->insertAll($list);

        /**/


//        $userinfo = $this->wechat->instance('user')->getUserInfo('otuUG0xq9K9K16Pkj3C55m99C8SY');
//        $data = array(
//            'openid' => $userinfo['openid'],
//            'nickname' => $userinfo['nickname'],
//            'sex' => $userinfo['sex'],
//            'city' => $userinfo['city'],
//            'province' => $userinfo['province'],
//            'headimgurl' => $userinfo['headimgurl'],
//            'create_time' => time(),
//        );
//        model('wechatmessage')->save($data);

        $data = $this->request->param();
        $post['nickname'] = isset($data['nickname'])?$data['nickname']:'';
        $post['times'] =isset($data['times'])?$data['times']:'';
        $post['need'] =isset($data['need'])?$data['need']:'';
        $post['sex'] = isset($data['sex'])?$data['sex']:'';

        $list = db('wuser')->where($this->datas)->paginate()->appends($this->request->param());

        $this->assign('list', $list);
        $this->assign('num',db('wuser')->count());
        $this->assign('post', $post);
        return $this->fetch();

    }

    /**
        群
    */
    public function index(){

        $data= db('wgroups')->select();
        if(empty($data)){
            $group = $this->wechat->instance('group')->getAllGroups();
        }

        if(!empty($group)){
            foreach($group['groups'] as $key =>$value){
                $list[$key]['id'] = $value['id'];
                $list[$key]['name'] = $value['name'];
            }
            db('wgroups')->insertAll($list);
        }

        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
    用户列表
    */
    public function userlist2(){
		
		/** 写入数据库*
            $data = $this->wechat->instance('user')->getUserLists();
            $value['user_list'] = null;
            foreach ($data['data']['openid'] as $key) {
                $value['user_list'][] = [
                    "openid" => "$key",
                    "lang" => "zh_CN",
                ];
            }
            $user = $this->wechat->instance('user')->getUserInfoLists($value);

		foreach($user['user_info_list'] as $key =>$value){
			
			$list[$key]['openid'] = $value['openid'];
			$list[$key]['groupid'] = $value['groupid'];
			$list[$key]['subscribe'] = $value['subscribe'];
			$list[$key]['nickname'] = $value['nickname'];
			$list[$key]['sex'] = $value['sex'];
			$list[$key]['city'] = $value['city'];
			$list[$key]['country'] = $value['country'];
			$list[$key]['province'] = $value['province'];
			$list[$key]['headimgurl'] = $value['headimgurl'];
			$list[$key]['subscribe_time'] = $value['subscribe_time'];
		}
			$res= db('wuser')->insertAll($list);
			
            /**/

        $list = db('wuser')->where('groupid',$this->request->param('groupid'))->paginate();

        $wgroups= db('wgroups')->select();
        $this->assign('wgroups', $wgroups);
        $this->assign('list', $list);
        $this->assign('num', db('wuser')->where('groupid',$this->request->param('groupid'))->count());
        return $this->fetch();

    }


    /**
    添加群
    */
    public function add(){
        return $this->fetch('edit');
    }

    /**
    编辑群
    */
    public function edit($id){
        return $this->fetch();
    }


    /**
    删除群
    */
    public function del($id){
         $jsonstr = ["group"=>
                        ["id"=>$id]
                    ];
            $data = $this->wechat->instance('group')->delGroup($jsonstr);

            if($data =='1'){
                    db('wgroups')->where('id',$id)->delete();
                   $this->success('删除成功');
                } else {
                    $this->error($data['errmsg'].'删除失败');
                }
    }


    /**
    保存群
    */
    public function save(){
        if (!$this->request->isPost()) {
            return ajax_info('请求失败');
        }
        if($this->request->post('id')){
                             $jsonstr = ["group"=>
                        ["id"=>$this->request->post('id'),"name"=>$this->request->post('name')]
                                ];
                        $data = $this->wechat->instance('group')->changeGroupName($jsonstr);
             
        }else{
                    $jsonstr = ["group"=>
                        ["name"=>$this->request->post('name')]
                    ];
                    $data = $this->wechat->instance('group')->create($jsonstr);
    
        }

           if(isset($data['group'])||$data =='1'){
                if($this->request->post('id')){
                   db('wgroups')->where(['id'=>$this->request->post('id')])->update(['name' => $this->request->post('name')]); 
                   }else{
                        db('wgroups')->insert(["id"=>$data['group']['id'],'name' =>$data['group']['name']]); 
                   }
                    

                    return ajax_info('保存成功','u');
                }else{
                    return ajax_info($data['errmsg'] . ',没有修改','u');
                }


    }



    /**
     * 移动用户
     */
    public function move_user()
    {

        $post = $this->request->post();
        if (empty($post['openid'])) {
            return ajax_info('请选择用户！', 'index');
        }

        $list = array();
        foreach ($post['openid'] as $key=>$value) {
            
                    $list["openid_list"][$key] = $value;
                }
                    
		$groupid = ["to_groupid"=>$post['groupsid']];
					
                  $jsonstr = array_merge($list,$groupid);


        $data = $this->wechat->instance('group')->moveUserToGroup($jsonstr);
        if($data =='1'){

                  foreach ($list['openid_list'] as $key => $value) {
                     db('wuser')->where(['openid'=>$value])->update(['groupid'=>$post['groupsid']]);
                      }
                       return ajax_info('用户移动成功','u');
        }else{
             return ajax_info($data['errmsg'] . ',没有移动','u');
        }
    }


    /**
     * 同步用户
     * @return \think\response\View
     */
    public function SynFriends()
    {
        ini_set('max_execution_time', '0');
        $this->assign('url', '');
        $this->assign('jdtCss', '');
        $page = input('page');
        $page = $page ? $page : 0;
        $IN = input();
        $next_openid = isset($IN['next_openid']) ? $IN['next_openid'] : null;
        $wechatObj = $this->wechat->instance('user');
        $table = config('database.prefix') . 'syn_openid';
        $sql = "DELETE FROM {$table} WHERE openid IN (SELECT * FROM(SELECT openid FROM {$table}  GROUP BY openid HAVING COUNT(openid) > 1) AS b) AND id NOT IN (SELECT * FROM (SELECT MIN(id) FROM {$table}  GROUP BY openid HAVING COUNT(openid) > 1) AS c)";
        Db::execute($sql);
       // $opneidTotal = db('syn_openid')->count('distinct(openid)');
        $opneidTotal = db('syn_openid')->distinct(true)->field('openid')->count();
        $friendTotal = session( 'friendTotal');
        if ($opneidTotal >= $friendTotal  && $friendTotal >0) {
            $synOpenids = db('syn_openid')
                ->distinct(true)
                ->field('openid')
                ->paginate(100);
            if (!empty($synOpenids->items())) {
                $openids['user_list'] = [];
                foreach ($synOpenids as $key => $val) {
                    $openids['user_list'][$key]['openid'] = $val['openid'];
                }
                $friends_array = $wechatObj->getUserInfoLists($openids);
                if (isset($friends_array['user_info_list']) && is_array($friends_array['user_info_list'])) {
                    foreach ($friends_array['user_info_list'] as $value) {
                        $value['tagid_list'] = @json_encode($value['tagid_list'], true);
                        if (db('wuser')->where([ 'openid' => $value['openid']])->field('id')->find()) {
                            db('wuser')->where([ 'openid' => $value['openid']])->update($value);
                        } else {
                            db('wuser')->insert($value);
                        }
                    }
                }
                $url = url('SynFriends', ['page' => $page + 1]);
                $jdtCss = abs(ceil(((100 * $page / $friendTotal) * 100)));
                if ($jdtCss > 100) {
                    $jdtCss = 100;
                }
                $this->assign('text', $jdtCss . '%');
                $this->assign('jdtCss', $jdtCss . '%');
                $this->assign('url', $url);
            } else {
                $this->assign('jdtCss', '100%');
                $this->assign('text', '同步完成');
                db('syn_openid')->where('1=1')->delete();
            }
            return view('friend');
        }
        $friendList = $wechatObj->getUserLists($next_openid);//$wechatObj->getUserList($next_openid);
        session( 'friendTotal', $friendList['total']);
        if (!empty($friendList) && $friendList['count'] > 0) {
            $openids = array_chunk($friendList['data']['openid'], 5000);
            foreach ($openids as $key => $val) {
                foreach ($val as $key1 => $opneid) {
                    $openid_list[$key][$key1] = [
                        'openid' => $opneid,
                    ];
                }
                db('syn_openid')->insertAll($openid_list[$key]);
            }
            $url = url('SynFriends', ['next_openid' => $friendList['next_openid']]);
            $jdtCss = abs(ceil(($opneidTotal / $friendList['total'] * 100)));
            $this->assign('text', '同步openid');
            $this->assign('jdtCss', $jdtCss . '%');
            $this->assign('url', $url);
            return view('friend');
        } else {
            if ($wechatObj['errcode'] != '40001' && $wechatObj['errcode'] != '' && $wechatObj['errmsg'] != '') {

                    exit('errCode:' . $wechatObj['errcode'] . 'errMsg:' . $wechatObj['errmsg']);

            }
            $this->assign('jdtCss', '100%');
            $this->assign('text', '同步完成');
            return view('friend');
        }
    }

    /**
     * 同步选择的用户
     */
    public function synSelect()
    {
        $IN = input();
        if (!empty($IN) && isset($IN['openids'])) {
            $wechatObj =  $this->wechat->instance('user');
            $friends = [];
            foreach ($IN['openids'] as $key => $val) {
                $results = $wechatObj->getUserInfo($val);

                if(isset($results['errcode'])){
                    $update = true;
                    continue;
                }
                if ($results) {
                    $friends[$key] = $results;
                    $friends[$key]['tagid_list'] = json_encode($friends[$key]['tagid_list']);
                    if (!empty($friends[$key])) {
                        if (db('wuser')->where('openid' ,$val)->find()) {
                            db('wuser')->where('openid' ,$val)->update($friends[$key]);
                            $update = true;
                        } else {
                            $insert = db('wuser')->where( 'openid' , $val)->insert($friends[$key]);
                        }
                    }
                } else {
                    if ($wechatObj['errcode'] != '40001' && $wechatObj['errcode'] != '' && $wechatObj['errmsg'] != '') {
                        ajaxMsg('0', $wechatObj['errmsg']);
                    } else {
                        ajaxMsg('0', '遇到错误：errCode:' . $wechatObj['errcode'] . 'errMsg:' . $wechatObj['errmsg']);
                    }

                }
            }
            if ($update || $insert) {
                ajaxMsg('1', '同步成功');
            }

        } else {
            ajaxMsg('0', '你没有选择要同步的粉丝');
        }

    }


    /**
     * 发送消息
     */
    public function save11()
    {
        //指定用户
//        $data = "bbbbbbfdfdsvkcxvxc大师傅大师傅";
//        $res  = $this->wechat->instance('Customservice')->sendImage("otuUG0ztt5Wl_KnUs0T_dK9_2tXg",$data);
//        dump($res);
//        exit();
//        //指定用户
//        $data = "bbbbbbfdfdsvkcxvxc大师傅大师傅";
//        $res  = $this->wechat->instance('Customservice')->sendTest("otuUG0ztt5Wl_KnUs0T_dK9_2tXg",$data);
//        dump($res);
//        exit();

        //可以群发信息了

        $data = [
            "filter"			=> [
                "is_to_all" 	=> true,
            ],

            "text"              => [
                "content" => "你觉得呢？！成功了！要怎么利用呢？!1"
            ],
            "msgtype"             => "text"
        ];
        $res  = $this->wechat->instance('message')->sendAll($data);
        dump($res);
        exit();
        $dd =$this->wechat->instance('material')->upload('image','../public/uploads/sm_avatar.png',1);
//        $dd =$this->wechat->instance('material')->total();
        dump($dd);
        exit();
        $data = [
            "touser"  => "otuUG0ztt5Wl_KnUs0T_dK9_2tXg",
            "mpnews"  => [
                "media_id" => "vy-Bt5ys21PaDtHwY8DXhW2Z7KDpIU9_S1k2lA-4FGfDSoxdZBUkmM-Q9JFk-nRq",
            ],
            "msgtype" => "mpnews",
        ];


        $aa = $this->wechat->instance('message')->preview($data);
        dump($aa);

    }
}
